package nl.windgazer.arachne.services.yql;

import org.apache.tapestry5.json.JSONObject;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class YQLRSSEntryImp implements YQLRSSEntry {

	public final static DateTimeFormatter RSS_PUBLISHEDDATE_FORMAT= DateTimeFormat.forPattern("EEE, dd MMM yyyy HH:mm:ss");

	public final static String SOURCE = "generic_rss";

	protected String title = null;

	protected String link = null;

	protected String desc = null;

	protected String auth = null;

	protected DateTime pub = null;

	//Constructors

	protected YQLRSSEntryImp(){};

	public YQLRSSEntryImp(JSONObject o) {
		this.title = o.getString("title");
		this.desc = o.getString("description");
		this.auth = null;
		this.link = o.getString("link");
		this.pub = getDateTime(o.getString("pubDate"));
	}
	
	//helpers

	public static DateTime getDateTime(final String rssdate) {
		return RSS_PUBLISHEDDATE_FORMAT.parseDateTime(rssdate.substring(0, rssdate.lastIndexOf(' ')));
	}

	//methods

	/**
	 * Last date first...
	 */
	public int compareTo(YQLRSSEntry o) {
		final long dif = getDatePublished().getMillis() - o.getDatePublished().getMillis();
		if (dif > 0) {
			return -1;
		} else if (dif < 0) {
			return 1;
		}
		return 0;
	}

	public String getTitle() {
		return title;
	}

	public String getDescription() {
		return desc;
	}

	public String getAuthor() {
		return auth;
	}

	public DateTime getDatePublished() {
		return pub;
	}

	public String getLink() {
		return link;
	}

	public String getSourceType() {
		return SOURCE;
	}

}
